package com.example.weibo_suhuanzhen.fragments;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.weibo_suhuanzhen.LoginEvent;
import com.example.weibo_suhuanzhen.R;
import com.example.weibo_suhuanzhen.UserSession;
import com.example.weibo_suhuanzhen.activities.LoginActivity;
import com.example.weibo_suhuanzhen.bean.UserInfo;
import com.example.weibo_suhuanzhen.retrofit.ShzApi;
import com.example.weibo_suhuanzhen.retrofit.RetrofitManager;
import com.example.weibo_suhuanzhen.sharedPreferences.SharedPreferencesManager;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoggedInFragment extends Fragment implements View.OnClickListener  {
    private static final int REQUEST_CODE_LOGIN = 100;
    final String TAG = "loggedInFragment";
    private TextView tv_username;
    private TextView tv_fans;
    private View view;
    private TextView tv_moment;
    private TextView logout;
    private ImageView im_avatar;
    private SharedPreferencesManager preferences;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_my,container,false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        this.view=view;
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        preferences = SharedPreferencesManager.getInstance(getContext());
        tv_username=view.findViewById(R.id.tv_username);
        im_avatar=view.findViewById(R.id.im_avatar);
        tv_moment=view.findViewById(R.id.moment);
        tv_fans=view.findViewById(R.id.tv_fans);
        logout=view.findViewById(R.id.top_right);
        updateUserInfo();
//        if (UserSession.getInstance().isLoggedIn()){
//            initLoggedView();
//        }else {
//            initLoginView();
//        }
    }


    private void updateUserInfo() {
        String token = preferences.getData("token","");
        if (token != null && !token.equals("")) {
            ShzApi api = RetrofitManager.getInstance().createApi();
            Call<ShzApi.UserInfoResponse> call = api.getUserInfo("Bearer " + token);
            call.enqueue(new Callback<ShzApi.UserInfoResponse>() {
                @Override
                public void onResponse(Call<ShzApi.UserInfoResponse> call, Response<ShzApi.UserInfoResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().getCode() == 403){
                            UserSession.getInstance().setLoggedIn(false);
                            preferences.saveData("token","");
                            preferences.saveBoolean("isLoggedIn",false);
                            UserSession.getInstance().setLoggedIn(false);
                            initLoginView();
                            Toast.makeText(getContext(),"token已过期，请重新登录",Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getContext(), LoginActivity.class);
                            startActivity(intent);
                        }else{
                            initLoggedView();
                            UserInfo userInfo = response.body().getData();
                            tv_username.setText(userInfo.getUsername());
                            if (userInfo.getAvatar() != null) {
                                Glide.with(LoggedInFragment.this)
                                        .load(userInfo.getAvatar())
                                        .transform(new CircleCrop())
                                        .into(im_avatar);
                            }
                        }

                    } else {
                        initLoginView();
                    }
                }

                @Override
                public void onFailure(Call<ShzApi.UserInfoResponse> call, Throwable t) {
                    Toast.makeText(getActivity(), "加载用户信息失败", Toast.LENGTH_SHORT).show();
                    initLoginView();
                }
            });
        } else {
            initLoginView();
        }
    }




    public void initLoggedView(){
        Log.d(TAG, "initLoggedView: 刷新已登录");

        im_avatar.setClickable(false);
        tv_moment.setText("快来发一条动态吧");
        tv_username.setText("用户名");
        tv_fans.setText("粉丝数：9999");
        logout.setVisibility(View.VISIBLE);
        logout.setOnClickListener(this);

    }

    public void initLoginView(){
        Log.d(TAG, "initLoggedView: 刷新未登录");

        im_avatar.setOnClickListener(this);
        logout.setVisibility(View.INVISIBLE);
        logout.setClickable(false);
        tv_moment.setText("登录查看更多");
        tv_username.setText("请先登录");
        tv_fans.setText("点击头像去登录");
        im_avatar.setImageResource(R.drawable.avatar_1);
    }
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.im_avatar:
                login();
                break;
            case R.id.top_right:
                UserSession.getInstance().setLoggedIn(false);
                preferences.saveData("token","");
                EventBus.getDefault().post(new LoginEvent()); // 发送登录事件
                initLoginView();
                break;
        }
    }

    private void login(){
        Intent intent=new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, REQUEST_CODE_LOGIN);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN && resultCode == RESULT_OK) {
            if (data != null && data.getBooleanExtra("login_success", false)) {
                // 刷新界面
                if (UserSession.getInstance().isLoggedIn()) {
                    initLoggedView();
                    updateUserInfo();
                }
            }
        }
    }
}
